<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>9.加上纹理</title>
</head>
<body>
	<canvas id="canvas"></canvas>
	<script src="https://webglfundamentals.org/webgl/resources/webgl-utils.js"></script>
	<script src="https://webglfundamentals.org/webgl/resources/m4.js"></script>
	<script src="https://webglfundamentals.org/webgl/resources/primitives.js"></script>
	<script src="https://webglfundamentals.org/webgl/resources/texture-utils.js"></script>
	<script src="https://webglfundamentals.org/webgl/resources/chroma.min.js"></script>
	<script type="x-shader/x-vertex" id="vertex">
		attribute vec4 a_position;

		uniform mat4 u_projection;
		uniform mat4 u_view;
		uniform mat4 u_world;
		attribute vec2 a_texcoord;
		
		varying vec2 v_texCoord;
		void main(){
			gl_Position =  u_projection * u_view * u_world * a_position;
			v_texCoord=a_texcoord;
		}
	</script>
	<script type="x-shader/x-fragment" id="fragment">
		precision mediump float;
		
		uniform sampler2D u_texture;
		varying vec2 v_texCoord;
		void main(){
			vec4 diffuseColor = texture2D(u_texture, v_texCoord);//纹理
			gl_FragColor = diffuseColor;
		}
	</script>
	<script>
		const canvas = document.getElementById("canvas");
		const gl = canvas.getContext("webgl")
		const aspect = gl.canvas.clientWidth/ gl.canvas.clientHeight;
		const programInfo=webglUtils.createProgramInfo(gl,["vertex","fragment"])
		const planeBufferInfo = primitives.createPlaneBufferInfo(
			gl,
			20,  // width
			20,  // height
			1,   // subdivisions across
			1,   // subdivisions down
		);
		gl.useProgram(programInfo.program)
		const cameraMatrix = m4.lookAt([10,10,10],[0,0,0],[0,1,0])
		const viewMatrix=m4.inverse(cameraMatrix)
		function degToRad(d) {
			return d * Math.PI / 180;
		}
		
		const texture = gl.createTexture();
		const image = new Image();
		// 图像加载完成后的回调函数
		image.onload = function() {
			// 将图像绑定到纹理对象
			
			gl.bindTexture(gl.TEXTURE_2D, texture);
			// 设置纹理参数
			gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
			gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
			gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
			gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
			
			// 将图像数据加载到纹理对象中
			gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
			
			const projectionMatrix=m4.perspective(degToRad(60), aspect, 1, 2000);
			webglUtils.setBuffersAndAttributes(gl, programInfo, planeBufferInfo);
			webglUtils.setUniforms(programInfo, {
				u_view: viewMatrix,					//视图
				u_projection: projectionMatrix,		//投影
				u_world:m4.translation(0, 0, 0),	//世界
			});
			webglUtils.drawBufferInfo(gl, planeBufferInfo);
		};
		// 设置图像的 URL
		image.src = '/17男性角色.svg';
	</script>
</body>
</html>